#include "consumptiondetailpage.h"
#include "../database/database.h"
#include "../services/consumptionservice.h"
#include "../appinitializer.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QStandardPaths>
#include <QApplication>
#include <QDebug>
#include <QSortFilterProxyModel>
#include <QPainter>
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrinter>
#include <QTextDocument>
#include <QDesktopServices>
#include <QUrl>

ConsumptionDetailPage::ConsumptionDetailPage(QWidget *parent)
    : QWidget(parent)
    , m_db(AppInitializer::database())
    , m_consumptionService(nullptr)
    , m_mainLayout(nullptr)
    , m_mainSplitter(nullptr)
    , m_filterGroup(nullptr)
    , m_memberCombo(nullptr)
    , m_levelCombo(nullptr)
    , m_statusCombo(nullptr)
    , m_paymentMethodCombo(nullptr)
    , m_searchBtn(nullptr)
    , m_resetBtn(nullptr)
    , m_refreshBtn(nullptr)
    , m_dataTable(nullptr)
    , m_statisticsGroup(nullptr)
    , m_statisticsLayout(nullptr)
    , m_totalOrdersLabel(nullptr)
    , m_totalAmountLabel(nullptr)
    , m_totalDiscountLabel(nullptr)
    , m_avgOrderAmountLabel(nullptr)
    , m_memberCountLabel(nullptr)
    , m_dateRangeLabel(nullptr)
    , m_discountRateBar(nullptr)
    , m_buttonLayout(nullptr)
    , m_viewDetailsBtn(nullptr)
    , m_sortByTimeBtn(nullptr)
    , m_sortByAmountBtn(nullptr)
    , m_exportBtn(nullptr)
    , m_printBtn(nullptr)
    , m_timeSortAscending(false)
    , m_amountSortAscending(false)
    , m_lastSortColumn(-1)
    , m_lastSortOrder(Qt::AscendingOrder)
    , m_refreshTimer(nullptr)
{
    // 初始化消费服务
    m_consumptionService = new ConsumptionService(m_db);
    
    // 初始化定时器
    m_refreshTimer = new QTimer(this);
    m_refreshTimer->setSingleShot(true);
    connect(m_refreshTimer, &QTimer::timeout, this, &ConsumptionDetailPage::loadConsumptionData);
    
    // 初始化UI
    initUI();
    
    // 加载初始数据
    loadMemberList();
    loadLevelList();
    loadPaymentMethods();
    loadConsumptionData();
}

ConsumptionDetailPage::~ConsumptionDetailPage()
{
    delete m_consumptionService;
}

void ConsumptionDetailPage::initUI()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(10, 10, 10, 10);
    m_mainLayout->setSpacing(10);
    
    // 创建主分割器
    m_mainSplitter = new QSplitter(Qt::Vertical, this);
    m_mainLayout->addWidget(m_mainSplitter);
    
    // 创建各个面板
    createFilterPanel();
    createDataTable();
    createStatisticsPanel();
    
    // 应用绿色主题
    applyGreenTheme();
}

void ConsumptionDetailPage::createFilterPanel()
{
    // 创建筛选面板组框
    m_filterGroup = new QGroupBox("筛选条件", this);
    m_filterGroup->setFixedHeight(100);
    m_mainSplitter->addWidget(m_filterGroup);
    
    // 创建横向布局
    QHBoxLayout *mainFilterLayout = new QHBoxLayout(m_filterGroup);
    mainFilterLayout->setContentsMargins(25, 30, 25, 15);
    mainFilterLayout->setSpacing(25);
    
    // 会员选择
    QLabel *memberLabel = new QLabel("会员选择:", m_filterGroup);
    memberLabel->setMinimumWidth(90);
    m_memberCombo = new QComboBox(m_filterGroup);
    m_memberCombo->setMinimumWidth(160);
    
    // 会员等级
    QLabel *levelLabel = new QLabel("会员等级:", m_filterGroup);
    levelLabel->setMinimumWidth(90);
    m_levelCombo = new QComboBox(m_filterGroup);
    m_levelCombo->setMinimumWidth(130);
    
    // 订单状态
    QLabel *statusLabel = new QLabel("订单状态:", m_filterGroup);
    statusLabel->setMinimumWidth(90);
    m_statusCombo = new QComboBox(m_filterGroup);
    m_statusCombo->setMinimumWidth(130);
    
    // 支付方式
    QLabel *paymentLabel = new QLabel("支付方式:", m_filterGroup);
    paymentLabel->setMinimumWidth(90);
    m_paymentMethodCombo = new QComboBox(m_filterGroup);
    m_paymentMethodCombo->setMinimumWidth(130);
    
    // 操作按钮
    m_searchBtn = new QPushButton("查询", m_filterGroup);
    m_resetBtn = new QPushButton("重置", m_filterGroup);
    
    // 设置按钮尺寸
    m_searchBtn->setMinimumWidth(90);
    m_resetBtn->setMinimumWidth(90);
    
    // 添加控件到横向布局
    mainFilterLayout->addWidget(memberLabel);
    mainFilterLayout->addWidget(m_memberCombo);
    mainFilterLayout->addSpacing(10);
    mainFilterLayout->addWidget(levelLabel);
    mainFilterLayout->addWidget(m_levelCombo);
    mainFilterLayout->addSpacing(10);
    mainFilterLayout->addWidget(statusLabel);
    mainFilterLayout->addWidget(m_statusCombo);
    mainFilterLayout->addSpacing(10);
    mainFilterLayout->addWidget(paymentLabel);
    mainFilterLayout->addWidget(m_paymentMethodCombo);
    mainFilterLayout->addSpacing(20);
    mainFilterLayout->addWidget(m_searchBtn);
    mainFilterLayout->addWidget(m_resetBtn);
    mainFilterLayout->addStretch();
    
    // 连接信号槽
    connect(m_memberCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ConsumptionDetailPage::onMemberFilterChanged);
    connect(m_levelCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ConsumptionDetailPage::onLevelFilterChanged);
    connect(m_statusCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ConsumptionDetailPage::onStatusFilterChanged);
    connect(m_paymentMethodCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ConsumptionDetailPage::onPaymentMethodChanged);
    connect(m_searchBtn, &QPushButton::clicked, this, &ConsumptionDetailPage::onSearchButtonClicked);
    connect(m_resetBtn, &QPushButton::clicked, this, &ConsumptionDetailPage::onResetFiltersClicked);
    
    setupFilterPanelStyle();
}

void ConsumptionDetailPage::createDataTable()
{
    // 创建数据表格
    m_dataTable = new QTableWidget(this);
    m_dataTable->setColumnCount(COLUMN_COUNT);
    
    // 设置表头
    QStringList headers;
    headers << "订单号" << "会员姓名" << "会员等级" << "消费时间" 
            << "消费金额" << "优惠金额" << "实付金额" << "支付方式" << "订单状态";
    m_dataTable->setHorizontalHeaderLabels(headers);
    
    // 设置表格属性
    m_dataTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_dataTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_dataTable->setAlternatingRowColors(true);
    m_dataTable->setSortingEnabled(true);
    m_dataTable->verticalHeader()->setVisible(false);
    
    // 设置列宽
    m_dataTable->horizontalHeader()->setStretchLastSection(true);
    m_dataTable->setColumnWidth(COLUMN_ORDER_ID, 80);
    m_dataTable->setColumnWidth(COLUMN_MEMBER_NAME, 100);
    m_dataTable->setColumnWidth(COLUMN_MEMBER_LEVEL, 80);
    m_dataTable->setColumnWidth(COLUMN_ORDER_TIME, 150);
    m_dataTable->setColumnWidth(COLUMN_TOTAL_AMOUNT, 100);
    m_dataTable->setColumnWidth(COLUMN_DISCOUNT_AMOUNT, 100);
    m_dataTable->setColumnWidth(COLUMN_FINAL_AMOUNT, 100);
    m_dataTable->setColumnWidth(COLUMN_PAYMENT_METHOD, 100);
    
    // 连接信号槽
    connect(m_dataTable->horizontalHeader(), &QHeaderView::sectionClicked, this, &ConsumptionDetailPage::onTableHeaderClicked);
    connect(m_dataTable, &QTableWidget::itemDoubleClicked, this, &ConsumptionDetailPage::onTableItemDoubleClicked);
    
    m_mainSplitter->addWidget(m_dataTable);
    setupTableStyle();
}

void ConsumptionDetailPage::createStatisticsPanel()
{
    // 创建统计面板组框
    m_statisticsGroup = new QGroupBox("统计信息", this);
    m_statisticsGroup->setFixedHeight(120);
    m_mainSplitter->addWidget(m_statisticsGroup);
    
    // 创建统计面板布局
    m_statisticsLayout = new QGridLayout(m_statisticsGroup);
    m_statisticsLayout->setContentsMargins(15, 20, 15, 15);
    m_statisticsLayout->setSpacing(15);
    
    // 创建统计标签
    m_totalOrdersLabel = new QLabel("总订单数: 0", m_statisticsGroup);
    m_totalAmountLabel = new QLabel("总消费金额: ¥0.00", m_statisticsGroup);
    m_totalDiscountLabel = new QLabel("总优惠金额: ¥0.00", m_statisticsGroup);
    m_avgOrderAmountLabel = new QLabel("平均订单金额: ¥0.00", m_statisticsGroup);
    m_memberCountLabel = new QLabel("涉及会员数: 0", m_statisticsGroup);
    m_dateRangeLabel = new QLabel("统计时间范围: --", m_statisticsGroup);
    
    // 创建优惠率进度条
    QLabel *discountRateLabel = new QLabel("平均优惠率:", m_statisticsGroup);
    m_discountRateBar = new QProgressBar(m_statisticsGroup);
    m_discountRateBar->setRange(0, 100);
    m_discountRateBar->setValue(0);
    m_discountRateBar->setFormat("%p%");
    m_discountRateBar->setMaximumWidth(150);
    
    // 创建刷新按钮
    m_refreshBtn = new QPushButton("刷新", m_statisticsGroup);
    m_refreshBtn->setMinimumWidth(80);
    
    // 布局统计信息
    m_statisticsLayout->addWidget(m_totalOrdersLabel, 0, 0);
    m_statisticsLayout->addWidget(m_totalAmountLabel, 0, 1);
    m_statisticsLayout->addWidget(m_totalDiscountLabel, 0, 2);
    m_statisticsLayout->addWidget(m_avgOrderAmountLabel, 1, 0);
    m_statisticsLayout->addWidget(m_memberCountLabel, 1, 1);
    m_statisticsLayout->addWidget(m_dateRangeLabel, 1, 2);
    
    QHBoxLayout *progressLayout = new QHBoxLayout();
    progressLayout->addWidget(discountRateLabel);
    progressLayout->addWidget(m_discountRateBar);
    progressLayout->addStretch();
    progressLayout->setContentsMargins(0, 0, 0, 0);
    QWidget *progressWidget = new QWidget();
    progressWidget->setLayout(progressLayout);
    m_statisticsLayout->addWidget(progressWidget, 0, 3, 1, 1);
    
    // 将刷新按钮放在最右侧
    m_statisticsLayout->addWidget(m_refreshBtn, 1, 3);
    
    // 连接刷新按钮信号槽
    connect(m_refreshBtn, &QPushButton::clicked, this, &ConsumptionDetailPage::onRefreshDataClicked);
    
    setupStatisticsPanelStyle();
}

// 底部功能按钮已移除

void ConsumptionDetailPage::loadConsumptionData()
{
    if (!m_consumptionService) {
        qDebug() << "消费服务未初始化";
        return;
    }
    
    // 获取所有消费记录
    m_originalData = m_consumptionService->getAllConsumptionForDisplay();
    m_currentData = m_originalData;
    
    // 更新表格显示
    updateTableData(m_currentData);
    
    // 更新统计信息
    updateStatisticsDisplay(m_currentData);
}

void ConsumptionDetailPage::loadMemberList()
{
    if (!m_memberCombo || !m_db) return;
    
    m_memberCombo->clear();
    m_memberCombo->addItem("全部会员", -1);
    
    // 从数据库加载会员列表，包含等级信息
    QString sql = "SELECT c.customer_id, c.name, c.level_id, ml.level_name FROM customer c "
                  "LEFT JOIN membership_level ml ON c.level_id = ml.level_id "
                  "ORDER BY c.name";
    QVector<QMap<QString, QVariant>> results = m_db->query(sql);
    
    for (const auto &row : results) {
        int customerId = row["customer_id"].toInt();
        QString customerName = row["name"].toString();
        int levelId = row["level_id"].toInt();
        QString levelName = row["level_name"].toString();
        
        // 根据会员等级显示不同的标识
        QString displayName;
        if (levelId == 0) {
            displayName = QString("%1 (非会员)").arg(customerName);
        } else {
            displayName = QString("%1 (%2)").arg(customerName, levelName);
        }
        
        m_memberCombo->addItem(displayName, customerId);
    }
}

void ConsumptionDetailPage::loadLevelList()
{
    if (!m_levelCombo) return;
    
    m_levelCombo->clear();
    m_levelCombo->addItem("全部等级", -1);
    m_levelCombo->addItem("非会员", 0);
    m_levelCombo->addItem("初级会员", 1);
    m_levelCombo->addItem("中级会员", 2);
    m_levelCombo->addItem("高级会员", 3);
}

void ConsumptionDetailPage::loadPaymentMethods()
{
    if (!m_paymentMethodCombo) return;
    
    m_paymentMethodCombo->clear();
    m_paymentMethodCombo->addItem("全部方式", "");
    m_paymentMethodCombo->addItem("现金", "现金");
    m_paymentMethodCombo->addItem("银行卡", "银行卡");
    m_paymentMethodCombo->addItem("支付宝", "支付宝");
    m_paymentMethodCombo->addItem("微信支付", "微信支付");
    
    if (!m_statusCombo) return;
    
    m_statusCombo->clear();
    m_statusCombo->addItem("全部状态", -1);
    m_statusCombo->addItem("待支付", 0);
    m_statusCombo->addItem("已支付", 1);
    m_statusCombo->addItem("已完成", 2);
    m_statusCombo->addItem("已取消", 3);
    m_statusCombo->addItem("已退款", 4);
}

void ConsumptionDetailPage::updateTableData(const QVector<QMap<QString, QVariant>> &data)
{
    if (!m_dataTable) return;
    
    m_dataTable->setRowCount(data.size());
    
    for (int row = 0; row < data.size(); ++row) {
        const auto &record = data[row];
        
        // 订单号
        QTableWidgetItem *orderIdItem = new QTableWidgetItem(record.value("order_id", "").toString());
        orderIdItem->setTextAlignment(Qt::AlignCenter);
        m_dataTable->setItem(row, COLUMN_ORDER_ID, orderIdItem);
        
        // 会员姓名
        QTableWidgetItem *memberNameItem = new QTableWidgetItem(record.value("customer_name", "非会员").toString());
        memberNameItem->setTextAlignment(Qt::AlignCenter);
        m_dataTable->setItem(row, COLUMN_MEMBER_NAME, memberNameItem);
        
        // 会员等级
        QTableWidgetItem *levelItem = new QTableWidgetItem(record.value("level_display_name", "非会员").toString());
        levelItem->setTextAlignment(Qt::AlignCenter);
        m_dataTable->setItem(row, COLUMN_MEMBER_LEVEL, levelItem);
        
        // 消费时间
        QTableWidgetItem *timeItem = new QTableWidgetItem(record.value("formatted_order_time", "--").toString());
        timeItem->setTextAlignment(Qt::AlignCenter);
        m_dataTable->setItem(row, COLUMN_ORDER_TIME, timeItem);
        
        // 消费金额
        QTableWidgetItem *totalAmountItem = new QTableWidgetItem(record.value("formatted_total_amount", "¥0.00").toString());
        totalAmountItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        m_dataTable->setItem(row, COLUMN_TOTAL_AMOUNT, totalAmountItem);
        
        // 优惠金额
        QTableWidgetItem *discountItem = new QTableWidgetItem(record.value("formatted_discount_amount", "¥0.00").toString());
        discountItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        m_dataTable->setItem(row, COLUMN_DISCOUNT_AMOUNT, discountItem);
        
        // 实付金额
        QTableWidgetItem *finalAmountItem = new QTableWidgetItem(record.value("formatted_final_amount", "¥0.00").toString());
        finalAmountItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        m_dataTable->setItem(row, COLUMN_FINAL_AMOUNT, finalAmountItem);
        
        // 支付方式
        QTableWidgetItem *paymentItem = new QTableWidgetItem(record.value("formatted_payment_method", "未知").toString());
        paymentItem->setTextAlignment(Qt::AlignCenter);
        m_dataTable->setItem(row, COLUMN_PAYMENT_METHOD, paymentItem);
        
        // 订单状态
        QTableWidgetItem *statusItem = new QTableWidgetItem(record.value("formatted_status", "未知").toString());
        statusItem->setTextAlignment(Qt::AlignCenter);
        
        // 根据状态设置颜色
        QString statusColor = record.value("status_color", "#000000").toString();
        statusItem->setForeground(QBrush(QColor(statusColor)));
        
        m_dataTable->setItem(row, COLUMN_ORDER_STATUS, statusItem);
    }
}

void ConsumptionDetailPage::updateStatisticsDisplay(const QVector<QMap<QString, QVariant>> &data)
{
    if (data.isEmpty()) {
        m_totalOrdersLabel->setText("总订单数: 0");
        m_totalAmountLabel->setText("总消费金额: ¥0.00");
        m_totalDiscountLabel->setText("总优惠金额: ¥0.00");
        m_avgOrderAmountLabel->setText("平均订单金额: ¥0.00");
        m_memberCountLabel->setText("涉及会员数: 0");
        m_discountRateBar->setValue(0);
        return;
    }
    
    // 计算统计数据
    int totalOrders = data.size();
    double totalAmount = 0.0;
    double totalDiscount = 0.0;
    QSet<int> memberIds;
    
    for (const auto &record : data) {
        totalAmount += record.value("total_amount", 0.0).toDouble();
        totalDiscount += record.value("discount_amount", 0.0).toDouble();
        
        int memberId = record.value("member_id", 0).toInt();
        if (memberId > 0) {
            memberIds.insert(memberId);
        }
    }
    
    double avgOrderAmount = totalOrders > 0 ? totalAmount / totalOrders : 0.0;
    double discountRate = totalAmount > 0 ? (totalDiscount / totalAmount) * 100 : 0.0;
    
    // 更新显示
    m_totalOrdersLabel->setText(QString("总订单数: %1").arg(totalOrders));
    m_totalAmountLabel->setText(QString("总消费金额: %1").arg(formatAmount(totalAmount)));
    m_totalDiscountLabel->setText(QString("总优惠金额: %1").arg(formatAmount(totalDiscount)));
    m_avgOrderAmountLabel->setText(QString("平均订单金额: %1").arg(formatAmount(avgOrderAmount)));
    m_memberCountLabel->setText(QString("涉及会员数: %1").arg(memberIds.size()));
    m_discountRateBar->setValue(static_cast<int>(discountRate));
    
    // 更新时间范围显示为全部数据
    m_dateRangeLabel->setText("统计时间范围: 全部数据");
}

void ConsumptionDetailPage::applyFilters()
{
    if (!m_consumptionService) return;
    
    QVector<QMap<QString, QVariant>> filteredData = m_originalData;
    
    // 按会员筛选
    int selectedMemberId = m_memberCombo->currentData().toInt();
    if (selectedMemberId > 0) {
        filteredData = m_consumptionService->filterConsumptionByMember(filteredData, selectedMemberId);
    }
    
    // 按等级筛选
    int selectedLevelId = m_levelCombo->currentData().toInt();
    if (selectedLevelId >= 0) {
        filteredData = m_consumptionService->filterConsumptionByLevel(filteredData, selectedLevelId);
    }
    
    // 按状态筛选
    int selectedStatus = m_statusCombo->currentData().toInt();
    if (selectedStatus >= 0) {
        filteredData = m_consumptionService->filterConsumptionByStatus(filteredData, selectedStatus);
    }
    
    // 按支付方式筛选
    QString selectedPaymentMethod = m_paymentMethodCombo->currentData().toString();
    if (!selectedPaymentMethod.isEmpty()) {
        filteredData = m_consumptionService->filterConsumptionByPaymentMethod(filteredData, selectedPaymentMethod);
    }
    
    m_currentData = filteredData;
    updateTableData(m_currentData);
    updateStatisticsDisplay(m_currentData);
}

QString ConsumptionDetailPage::formatAmount(double amount)
{
    return QString("¥%1").arg(QString::number(amount, 'f', 2));
}

QString ConsumptionDetailPage::formatDateTime(const QDateTime &dateTime)
{
    return dateTime.toString("yyyy-MM-dd hh:mm:ss");
}

// 槽函数实现
void ConsumptionDetailPage::onMemberFilterChanged()
{
    applyFilters(); // 立即执行筛选
}

void ConsumptionDetailPage::onLevelFilterChanged()
{
    applyFilters(); // 立即执行筛选
}



void ConsumptionDetailPage::onStatusFilterChanged()
{
    m_refreshTimer->start(300);
}

void ConsumptionDetailPage::onPaymentMethodChanged()
{
    m_refreshTimer->start(300);
}

void ConsumptionDetailPage::onSearchButtonClicked()
{
    applyFilters();
}

void ConsumptionDetailPage::onResetFiltersClicked()
{
    m_memberCombo->setCurrentIndex(0);
    m_levelCombo->setCurrentIndex(0);
    m_statusCombo->setCurrentIndex(0);
    m_paymentMethodCombo->setCurrentIndex(0);
    
    m_currentData = m_originalData;
    updateTableData(m_currentData);
    updateStatisticsDisplay(m_currentData);
}

void ConsumptionDetailPage::onRefreshDataClicked()
{
    // 重新加载所有数据
    loadMemberList();
    loadLevelList();
    loadPaymentMethods();
    loadConsumptionData();
}

void ConsumptionDetailPage::onSortByTimeClicked()
{
    m_timeSortAscending = !m_timeSortAscending;
    m_currentData = m_consumptionService->sortConsumptionByTime(m_currentData, m_timeSortAscending);
    updateTableData(m_currentData);
    
    m_sortByTimeBtn->setText(m_timeSortAscending ? "按时间排序↑" : "按时间排序↓");
}

void ConsumptionDetailPage::onSortByAmountClicked()
{
    m_amountSortAscending = !m_amountSortAscending;
    m_currentData = m_consumptionService->sortConsumptionByAmount(m_currentData, m_amountSortAscending);
    updateTableData(m_currentData);
    
    m_sortByAmountBtn->setText(m_amountSortAscending ? "按金额排序↑" : "按金额排序↓");
}

void ConsumptionDetailPage::onTableHeaderClicked(int logicalIndex)
{
    Qt::SortOrder order = (m_lastSortColumn == logicalIndex && m_lastSortOrder == Qt::AscendingOrder) 
                         ? Qt::DescendingOrder : Qt::AscendingOrder;
    
    m_dataTable->sortItems(logicalIndex, order);
    m_lastSortColumn = logicalIndex;
    m_lastSortOrder = order;
}

void ConsumptionDetailPage::onViewOrderDetailsClicked()
{
    int currentRow = m_dataTable->currentRow();
    if (currentRow < 0 || currentRow >= m_currentData.size()) {
        showStyledMessageBox(QMessageBox::Information, "提示", "请先选择一个订单记录");
        return;
    }
    
    int orderId = m_currentData[currentRow].value("order_id", 0).toInt();
    showOrderDetailsDialog(orderId);
}

void ConsumptionDetailPage::onTableItemDoubleClicked(QTableWidgetItem *item)
{
    if (!item || item->row() < 0 || item->row() >= m_currentData.size()) return;
    
    int orderId = m_currentData[item->row()].value("order_id", 0).toInt();
    showOrderDetailsDialog(orderId);
}

void ConsumptionDetailPage::onExportDataClicked()
{
    if (m_currentData.isEmpty()) {
        showStyledMessageBox(QMessageBox::Information, "提示", "没有数据可以导出");
        return;
    }
    
    QString fileName = QFileDialog::getSaveFileName(this, "导出消费明细", 
                                                   QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/消费明细.csv",
                                                   "CSV文件 (*.csv)");
    if (!fileName.isEmpty()) {
        exportToExcel(m_currentData);
        showStyledMessageBox(QMessageBox::Information, "成功", "数据导出成功！");
    }
}

void ConsumptionDetailPage::onPrintReportClicked()
{
    if (m_currentData.isEmpty()) {
        showStyledMessageBox(QMessageBox::Information, "提示", "没有数据可以打印");
        return;
    }
    
    printReport(m_currentData);
}

void ConsumptionDetailPage::onUpdateStatistics()
{
    updateStatisticsDisplay(m_currentData);
}



void ConsumptionDetailPage::showOrderDetailsDialog(int orderId)
{
    // 这里可以实现订单详情对话框
    showStyledMessageBox(QMessageBox::Information, "订单详情", QString("订单ID: %1\n详情功能待实现").arg(orderId));
}

void ConsumptionDetailPage::showStyledMessageBox(QMessageBox::Icon icon, const QString &title, const QString &text)
{
    QMessageBox msgBox(this);
    msgBox.setIcon(icon);
    msgBox.setWindowTitle(title);
    msgBox.setText(text);
    msgBox.setStyleSheet("QMessageBox { color: black; background-color: white; }");
    msgBox.exec();
}

void ConsumptionDetailPage::exportToExcel(const QVector<QMap<QString, QVariant>> &data)
{
    // 这里应该实现Excel导出功能
    Q_UNUSED(data)
    qDebug() << "导出Excel功能待实现";
}

void ConsumptionDetailPage::printReport(const QVector<QMap<QString, QVariant>> &data)
{
    // 这里应该实现打印功能
    Q_UNUSED(data)
    qDebug() << "打印功能待实现";
}

// 样式设置函数
void ConsumptionDetailPage::setupTableStyle()
{
    if (!m_dataTable) return;
    
    m_dataTable->setStyleSheet(
        "QTableWidget {"
        "    background-color: #FFFFFF;"
        "    border: 1px solid #4CAF50;"
        "    border-radius: 4px;"
        "    gridline-color: #E0E0E0;"
        "    selection-background-color: #C8E6C9;"
        "    font-size: 14px;"
        "}"
        "QTableWidget::item {"
        "    padding: 6px;"
        "    border-bottom: 1px solid #E0E0E0;"
        "    min-height: 20px;"
        "}"
        "QTableWidget::item:selected {"
        "    background-color: #A5D6A7;"
        "    color: #2E7D32;"
        "}"
        "QTableWidget::item:alternate {"
        "    background-color: #F1F8E9;"
        "}"
        "QHeaderView::section {"
        "    background-color: #4CAF50;"
        "    color: white;"
        "    padding: 6px;"
        "    border: none;"
        "    font-weight: bold;"
        "    font-size: 15px;"
        "    min-height: 25px;"
        "}"
    );
}

void ConsumptionDetailPage::setupFilterPanelStyle()
{
    if (!m_filterGroup) return;
    
    m_filterGroup->setStyleSheet(
        "QGroupBox {"
        "    font-weight: bold;"
        "    border: 2px solid #4CAF50;"
        "    border-radius: 10px;"
        "    margin-top: 10px;"
        "    background-color: #F1F8E9;"
        "    font-size: 16px;"
        "}"
        "QGroupBox::title {"
        "    subcontrol-origin: margin;"
        "    left: 15px;"
        "    padding: 0 8px 0 8px;"
        "    color: #2E7D32;"
        "    font-size: 17px;"
        "    font-weight: bold;"
        "}"
        "QLabel {"
        "    color: #2E7D32;"
        "    font-weight: bold;"
        "    font-size: 16px;"
        "    margin: 0px;"
        "    padding: 0px;"
        "}"
        "QComboBox {"
        "    border: 2px solid #81C784;"
        "    border-radius: 6px;"
        "    padding: 8px 12px;"
        "    background-color: white;"
        "    font-size: 15px;"
        "    min-height: 20px;"
        "    color: #2E7D32;"
        "}"
        "QComboBox::drop-down {"
        "    subcontrol-origin: padding;"
        "    subcontrol-position: top right;"
        "    width: 20px;"
        "    border-left-width: 1px;"
        "    border-left-color: #81C784;"
        "    border-left-style: solid;"
        "    border-top-right-radius: 6px;"
        "    border-bottom-right-radius: 6px;"
        "}"
        "QComboBox::down-arrow {"
        "    image: none;"
        "    border: 2px solid #4CAF50;"
        "    width: 8px;"
        "    height: 8px;"
        "    border-top: none;"
        "    border-left: none;"
        "    margin-top: 2px;"
        "}"
        "QComboBox QAbstractItemView {"
        "    border: 2px solid #81C784;"
        "    background-color: white;"
        "    color: #2E7D32;"
        "    font-size: 15px;"
        "    selection-background-color: #E8F5E8;"
        "    selection-color: #2E7D32;"
        "    outline: none;"
        "}"
        "QComboBox QAbstractItemView::item {"
        "    padding: 8px 12px;"
        "    border-bottom: 1px solid #E0E0E0;"
        "    color: #2E7D32;"
        "}"
        "QComboBox QAbstractItemView::item:selected {"
        "    background-color: #E8F5E8;"
        "    color: #2E7D32;"
        "}"
        "QComboBox QAbstractItemView::item:hover {"
        "    background-color: #F1F8E9;"
        "    color: #2E7D32;"
        "}"
        "QComboBox:focus {"
        "    border: 2px solid #4CAF50;"
        "    background-color: #F9FFF9;"
        "}"
        "QComboBox:hover {"
        "    border: 2px solid #66BB6A;"
        "    background-color: #F5F5F5;"
        "}"
        "QPushButton {"
        "    background-color: #4CAF50;"
        "    color: white;"
        "    border: none;"
        "    border-radius: 6px;"
        "    padding: 8px 16px;"
        "    font-size: 15px;"
        "    font-weight: bold;"
        "    min-height: 20px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #45A049;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #3D8B40;"
        "}"
    );
}

void ConsumptionDetailPage::setupStatisticsPanelStyle()
{
    if (!m_statisticsGroup) return;
    
    m_statisticsGroup->setStyleSheet(
        "QGroupBox {"
        "    font-weight: bold;"
        "    border: 2px solid #4CAF50;"
        "    border-radius: 10px;"
        "    margin-top: 10px;"
        "    background-color: #E8F5E8;"
        "    font-size: 16px;"
        "}"
        "QGroupBox::title {"
        "    subcontrol-origin: margin;"
        "    left: 12px;"
        "    padding: 0 8px 0 8px;"
        "    color: #2E7D32;"
        "    font-size: 17px;"
        "    font-weight: bold;"
        "}"
        "QLabel {"
        "    color: #1B5E20;"
        "    font-weight: bold;"
        "    font-size: 16px;"
        "    margin: 4px 0;"
        "    min-height: 24px;"
        "    padding: 2px 4px;"
        "}"
        "QProgressBar {"
        "    border: 1px solid #4CAF50;"
        "    border-radius: 5px;"
        "    text-align: center;"
        "    background-color: #FFFFFF;"
        "    font-size: 14px;"
        "    font-weight: bold;"
        "    min-height: 22px;"
        "}"
        "QProgressBar::chunk {"
        "    background-color: #4CAF50;"
        "    border-radius: 4px;"
        "}"
        "QPushButton {"
        "    font-size: 15px;"
        "    font-weight: bold;"
        "    min-height: 28px;"
        "    padding: 4px 8px;"
        "}"
    );
}

// 按钮样式设置函数已移除

void ConsumptionDetailPage::applyGreenTheme()
{
    // 设置整体背景
    this->setStyleSheet(
        "ConsumptionDetailPage {"
        "    background-color: #F1F8E9;"
        "}"
    );
}